package luj.tool.jnproxyan.proxy.admin.http.handle.invoke;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.common.template.TemplateEngine;
import luj.cluster.api.actor.Tellable;
import luj.tool.jnproxyan.framework.proxy.actor.tell.ActorTeller;
import luj.tool.jnproxyan.proxy.admin.AdminHttpHandler;
import luj.tool.jnproxyan.proxy.admin.AdminHttpModule;

import java.util.Map;

final class HandleContextImpl implements AdminHttpHandler.Context {

  @Override
  public AdminHttpHandler.Param param(String name) {
    ParamImpl param = new ParamImpl();
    param._name = name;
    param._value = _param.get(name);
    return param;
  }

  @Override
  public String encodeJson(Map<String, ?> value) {
    return encodeJsonImpl(value);
  }

  @Override
  public AdminHttpHandler.Ref actor(Class<?> type) {
    ActorRefImpl ref = new ActorRefImpl();
    ref._adminRef = _adminRef;
    ref._teller = _actorTeller;
    ref._targetActor = type;
    return ref;
  }

  @Override
  public void responsePage(Map<String, Object> model) {
    new HttpPageResponser(_vertx, _freeMarker, model,
        _rootModule, _vertx.currentRoute().getPath()).response();
  }

  private String encodeJsonImpl(Object value) {
    try {
      return JACKSON.writeValueAsString(value);
    } catch (JsonProcessingException e) {
      throw new UnsupportedOperationException(e);
    }
  }

  private static final ObjectMapper JACKSON = new ObjectMapper();

  Map<String, Object> _param;

  Tellable _adminRef;
  ActorTeller _actorTeller;

  RoutingContext _vertx;
  TemplateEngine _freeMarker;
  AdminHttpModule _rootModule;
}
